package com.study.utils;

import com.study.bean.UserInfo;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.executable.ExecutableValidator;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author zhuzi
 * 2023/8/11 10:02
 */
public class ValidationUtil {
    /**
     * 验证器-线程安全
     */
    private static Validator validator;
    private static Validator failFastValidator;
    private static ExecutableValidator executableValidator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
        failFastValidator = Validation.byProvider(HibernateValidator.class)
                //配置快速失败
                .configure().failFast(true).buildValidatorFactory().getValidator();
        //校验入参或者返回值
        executableValidator = validator.forExecutables();
    }

    public static <T> List<String> validNotBean(T object,
                                                Method method,
                                                Object[] parameterValues,
                                                Class<?>... groups) {
        Set<ConstraintViolation<T>> set = executableValidator.validateParameters(object, method, parameterValues, groups);
        return set.stream().map(v -> "属性:" + v.getPropertyPath() + ",属性的值" + v.getInvalidValue()
                        + ",校验不通过的提示信息:" + v.getMessage())
                .collect(Collectors.toList());
    }

    public static List<String> valid(UserInfo userInfo) {
        Set<ConstraintViolation<UserInfo>> set = validator.validate(userInfo);
        return set.stream().map(v -> "属性:" + v.getPropertyPath() + ",属性的值" + v.getInvalidValue()
                        + ",校验不通过的提示信息:" + v.getMessage())
                .collect(Collectors.toList());
    }

    public static List<String> valid(UserInfo userInfo, Class<?>... clazz) {
        Set<ConstraintViolation<UserInfo>> set = validator.validate(userInfo, clazz);
        return set.stream().map(v -> "属性:" + v.getPropertyPath() + ",属性的值" + v.getInvalidValue()
                        + ",校验不通过的提示信息:" + v.getMessage())
                .collect(Collectors.toList());
    }
}
